package com.alm.token.utils;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.widget.Toast;


import com.alm.token.ConStant;

import java.io.DataOutputStream;
import java.io.File;

public class ADBInstallApk {
    private static ADBInstallApk m_Instance = null;
    private adbInstallAPKListener adbInstallAPKListener;

    public static synchronized ADBInstallApk getInstance() {
        if (null == m_Instance) {
            m_Instance = new ADBInstallApk();
        }
        return m_Instance;
    }

    /**
     * 下载并安装APK  pm install -r APKpath
     */
    public void downloadApk(final Context mContext, String downloadUrl) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            String path = Environment.getExternalStorageDirectory().getAbsolutePath()
                    + File.separator
                    + "LOHAS"
                    + File.separator;
            DownloadUtil.getInstance()
                    .download(downloadUrl, path, new DownloadUtil.OnDownloadListener() {
                        @Override
                        public void onDownloadSuccess(String path) {
                            boolean isCom = runShellCommand(mContext, "pm install -r " + path);
                            if (isCom) {
                                SpUtil.putBoolean(mContext, "update_install", true);
                                Intent intent = new Intent();
                                intent.setAction("babiho.intent.action.APP_UPDATE");
                                intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
                                mContext.sendBroadcast(intent);
                            }
                        }

                        @Override
                        public void onDownloading(int progressm) {
                        }

                        @Override
                        public void onDownloadFailed() {
                        }
                    });
        }
    }

    /**
     * 下载并安装APK -> pm install -r {APKpath}
     *
     * @param apkName apk名字
     */
    public void downloadApk(final Context mContext, String downloadUrl, String apkName, final adbInstallAPKListener adbInstallAPKListener) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            final String path = Environment.getExternalStorageDirectory().getAbsolutePath()
                    + File.separator
                    + "LOHAS"
                    + File.separator;
            LogUtil.d( "分析:path "+path);
            LogUtil.e("downloadApk.downloadUrl="+downloadUrl);
            DownloadUtil.getInstance()
                    .download(downloadUrl, path, apkName, new DownloadUtil.OnDownloadListener() {
                        @Override
                        public void onDownloadSuccess(String path) {
                            LogUtil.d( "分析:"+"receive: 进入onDownloadSuccess");
//						  ADVideoDao mADVideoDao = DBHelper.getDaoSession().getADVideoDao();
//						  mADVideoDao.deleteAll();
//                            Toast.makeText(mContext, "receive: 进入onDownloadSuccess1", Toast.LENGTH_SHORT).show();

                            LogUtil.d( "apkpath"+ path);
                            adbInstallAPKListener.onDownloadSuccess(path);

//                            boolean isCom = runShellCommand(mContext, "pm install -r " + path);
//                            if (isCom) {
//                                Toast.makeText(mContext, "receive: 进入onDownloadSuccess2", Toast.LENGTH_SHORT).show();
//                                Intent intent = new Intent();
//                                intent.setAction("babiho.intent.action.APP_UPDATE");
//                                intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
//                                mContext.sendBroadcast(intent);
//
////                                Log.e("apkpath",file.getAbsolutePath());
////                                Intent intent = new Intent(Intent.ACTION_VIEW);
////                                intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
////                                startActivity(intent);
//
//                            }
                        }

                        @Override
                        public void onDownloading(int progressm) {
                            LogUtil.d( "分析:"+ "receive: 进入onDownloading");
//                            if (progressm % 5 == 0) {
//                                Toast.makeText(mContext, "进度=" + progressm, Toast.LENGTH_SHORT).show();
//                            }
                            adbInstallAPKListener.onDownloading(progressm);
                        }

                        @Override
                        public void onDownloadFailed() {
                            LogUtil.d( "分析:"+ "receive: 进入onDownloadFailed");
                        }
                    });
        }else {
            LogUtil.d( "232323");
        }
    }

    /**
     * 执行命令
     */
    public boolean runShellCommand(Context mContext, String cmd) {
        if (!getRootPermission(mContext)) {
            return false;
        }
        Process process = null;
        DataOutputStream os = null;
        try {
            process = Runtime.getRuntime().exec("su"); //切换到root帐号
            os = new DataOutputStream(process.getOutputStream());
            os.writeBytes(cmd + "\n");
            os.writeBytes("exit\n");
            os.flush();
            process.waitFor();
        } catch (Exception e) {
            return false;
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                process.destroy();
            } catch (Exception e) {
            }
        }
        return true;
    }

    /**
     * 检查是否拥有ROOT权限
     */
    public boolean getRootPermission(Context mContext) {
        Process process = null;
        DataOutputStream os = null;
        try {
            String cmd = "chmod 755 " + mContext.getPackageCodePath();
            process = Runtime.getRuntime().exec("su"); //切换到root帐号
            os = new DataOutputStream(process.getOutputStream());
            os.writeBytes(cmd + "\n");
            os.writeBytes("exit\n");
            os.flush();
            process.waitFor();
        } catch (Exception e) {
            return false;
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                process.destroy();
            } catch (Exception e) {
            }
        }
        return true;
    }

    public interface adbInstallAPKListener {
        /**
         * 下载成功
         */
        void onDownloadSuccess(String path);
        /**
         * 下载成功
         */
        void onDownloading(int progressm);
    }
}
